package cn.com.easy.sign;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import cn.com.easy.exception.BusinessException;

/**
 * 签名验证码工具类
 * 
 * @author nibili 2017年8月31日
 * 
 */
public class SignCaptchaUtil {

	/** 签名标签 */
	private final static String CAPTCHA_TAG = "CAPTCHA_TAG_SIGN_";

	/**
	 * 发送给客户端验证码
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author nibili 2017年8月31日
	 */
	public static String getCaptcha(HttpServletRequest request, SignBaseParamDto signBaseParamDto) throws BusinessException {
		String signId = signBaseParamDto.getSignCaptchaId();
		if (StringUtils.isBlank(signId) == true) {
			throw new BusinessException("signCaptchaId不能为空");
		}
		if (signId.length() > 20) {
			throw new BusinessException("signCaptchaId长度不能起过20");
		}
		String captcha = RandomStringUtils.random(4, "1234567890");
		request.getSession().setAttribute(CAPTCHA_TAG + signId, captcha.toLowerCase());
		return captcha;
	}

	/**
	 * 验正验证码
	 * 
	 * @param request
	 * @param clientString
	 * @return
	 * @author nibili 2017年8月31日
	 * @throws BusinessException
	 */
	public static boolean validCaptcha(HttpServletRequest request, SignBaseParamDto signBaseParamDto) throws BusinessException {
		if (StringUtils.isBlank(signBaseParamDto.getCaptcha()) == true) {
			throw new BusinessException("验证码不能为空");
		}
		String signId = signBaseParamDto.getSignCaptchaId();
		if (StringUtils.isBlank(signId) == true) {
			throw new BusinessException("signCaptchaId不能为空");
		}
		String inerCaptcha = (String) request.getSession().getAttribute(CAPTCHA_TAG + signId);
		String clientCaptcha = signBaseParamDto.getCaptcha();
		if (StringUtils.equals(inerCaptcha, clientCaptcha.toLowerCase()) == false) {
			// 不匹配
			return false;
		} else {
			request.getSession().removeAttribute(CAPTCHA_TAG + signId);
			return true;
		}
	}

}
